//
//  CreateAppointmentViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 12/10/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class CreateAppointmentViewController: UIViewController {

    @IBOutlet weak var locationTextField: CustomTextField!
    @IBOutlet weak var dateTimeTextField: CustomTextField!
    
    @IBOutlet weak var participantsAmountSlider:StepSlider!;
    
    @IBOutlet weak var aaPaymentButton: UIButton!
    @IBOutlet weak var meinPaymentButton: UIButton!
    @IBOutlet weak var notSurePaymentButton: UIButton!
    
    @IBOutlet weak var noteTextField: CustomTextField!
    @IBOutlet weak var inviteesTextView:UITextView!;
    @IBOutlet weak var inviteesView: UIView!
    
    var date:NSDate!;
    var paymentWay:String = "AA";
    var willInvitationPersons:[NSDictionary]!;
    
    
    var activeTextField:UITextField!;
    
    var adjustContentToAccommodateKeyboard:AdjustContentToAccommodateKeyboard!;
    
    var datePicker:AppointmentCustomDatePicker!;
    
    override func viewDidLoad() {
        super.viewDidLoad();
        self.hideTabBar();
        ViewUtils.addBackgroundView(self);
        self.initNavigation();
        self.textFieldPlaceHolder();
        self.initSlider();
        self.adjustContentToAccommodateKeyboard = AdjustContentToAccommodateKeyboard(target: self);
        self.dateTimeTextField.delegate = self;
    }
    
    func initSlider(){
        self.participantsAmountSlider.minValue = 2;
        self.participantsAmountSlider.maxValue = 6;
        self.participantsAmountSlider.value = 4;
        self.participantsAmountSlider.font = Utils.defaultFont();
        self.participantsAmountSlider.suffix = "人";
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.hideTabBar();
        self.fillDateTimeTextField();
        self.fillLocationTextFiedl();
        self.fillInviteesLabel();
    }
    
    func fillLocationTextFiedl(){
        var url = "/api/v1/appointment/lastlocation";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var lastLocation = response as NSDictionary;
            var location = lastLocation.objectForKey("location") as String;
            self.locationTextField.text = location;
        }, errorHandle: { (error) -> Void in
            
        });
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        if(self.datePicker == nil){
            var frame = CGRect(x: 0, y: self.dateTimeTextField.frame.origin.y + self.dateTimeTextField.frame.height + 5, width: self.view.frame.width, height: self.view.frame.height - (self.dateTimeTextField.frame.origin.y + self.dateTimeTextField.frame.height + 5));
            self.datePicker = AppointmentCustomDatePicker(frame: frame);
            self.datePicker.addTarget(self, action: Selector("dateChange:"), forControlEvents: UIControlEvents.ValueChanged);
            self.view.addSubview(self.datePicker);
        }
    }
  
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        if(textField.isEqual(dateTimeTextField)){
            UIApplication.sharedApplication().sendAction(Selector("resignFirstResponder"), to: nil, from: nil, forEvent: nil);
            self.datePicker.show();
            return false;
        }
        
        return true;
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.datePicker.hide();
    }
    
    func dateChange(datePicker:AppointmentCustomDatePicker){
        self.dateTimeTextField.text = datePicker.value;
    }
    
    func initNavigation(){
        var backButton = UIButton();
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.sizeToFit();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        var backBarItem = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarItem;
        
        var saveAppointmentButton = UIButton();
        saveAppointmentButton.setImage(UIImage(named: "confirm"), forState: UIControlState.Normal);
        saveAppointmentButton.showsTouchWhenHighlighted = true;
        saveAppointmentButton.sizeToFit();
        saveAppointmentButton.addTarget(self, action: Selector("saveAppointment:"), forControlEvents: UIControlEvents.TouchUpInside);
        var saveAppointmentBarItem = UIBarButtonItem(customView: saveAppointmentButton);
        self.navigationItem.rightBarButtonItem = saveAppointmentBarItem;
    }
    
    // Back
    func back(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    // Save appointment
    func saveAppointment(sender:UIButton){
        self.processing();
        var url = "/api/v1/appointment";
        
        var location = self.locationTextField.text;
        
        var dateFromTextField = self.dateTimeTextField.text;
      
        var dateAsString:String!;
        var periods:[String]!;
        if(datePicker != nil){
            dateAsString = DateUtils.toString(datePicker.date, format: "yyyy-MM-dd");
            periods = [datePicker.firstPeriodAsString,datePicker.secondPeriodAsString]
        } else {
            dateAsString = DateUtils.toString(NSDate(), format: "yyyy-MM-dd")
            periods = ["10:00","11:45"]
        }
        
        var participantsAmount = NSNumber(double: participantsAmountSlider.value).integerValue;
        var note = self.noteTextField.text;
        var invitees:[NSMutableDictionary] = [];
        for invitationPerson in self.willInvitationPersons{
            var invitee = invitationPerson.objectForKey("user") as NSMutableDictionary;
            invitees.append(invitee);
        }
        
        var httpBody = NSMutableDictionary();
        httpBody.setObject(location, forKey: "location");
        httpBody.setObject(dateAsString, forKey: "date");
        httpBody.setObject(periods, forKey: "periods");
        httpBody.setObject(participantsAmount, forKey: "participantsAmount");
        httpBody.setObject(self.paymentWay, forKey: "paymentWay");
        httpBody.setObject(note, forKey: "note");
        httpBody.setObject(invitees, forKey: "invitees");
        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: httpBody, successHandle: { (response) -> Void in
            self.saveAppointmentSuccess();
            self.processComplete();
        }, errorHandle: { (error) -> Void in
            self.processComplete();
        });
    }
    
    func saveAppointmentSuccess(){
        self.navigationController?.popToRootViewControllerAnimated(true);
    }
    
    func textFieldPlaceHolder(){
        self.locationTextField.addPlaceholder("打球地点");
        self.dateTimeTextField.addPlaceholder("打球时间");
        self.noteTextField.addPlaceholder("备注");
    }
    
    func fillDateTimeTextField(){
        var dateAsText = DateUtils.toString(self.date, format: "yyyy年MM月dd日");
        var currentHour = DateUtils.getCurrentHour();
        var currentMinute = DateUtils.getCurrentMinute();
        if(currentMinute % 15 != 0){
            currentMinute = ((currentMinute / 15) + 1) * 15;
        }
        if(currentMinute > 45){
            currentHour = currentHour + 1;
            currentMinute = 0;
        }
        
        var minuteAsString = currentMinute < 10 ? "0\(currentMinute)" : "\(currentMinute)";
        var startTime = "\(currentHour):\(minuteAsString)";
        var endTime = "\(currentHour + 2):\(minuteAsString)";
        self.dateTimeTextField.text = "\(dateAsText) \(startTime) - \(endTime)";
    }
    
    func fillInviteesLabel(){
        if(self.willInvitationPersons.isEmpty){
            self.inviteesView.hidden = true;
        } else {
            var inviteNames = "";
            for willInvitationPerson in self.willInvitationPersons{
                var user = willInvitationPerson.objectForKey("user") as NSMutableDictionary;
                var name = user.objectForKey("name") as String;
                inviteNames += "\(name) ";
            }
            self.inviteesTextView.text = inviteNames;
            self.inviteesTextView.textColor = UIColor.whiteColor();
            self.inviteesTextView.font = Utils.fontHupo(14);
        }
    }
    
    @IBAction func aaPayment(sender: UIButton) {
        if(sender.enabled){
            sender.enabled = false;
            self.paymentWay = "AA";
            sender.setBackgroundImage(UIImage(named: "payment_aa_checked"), forState: UIControlState.Normal);
            self.meinPaymentButton.enabled = true;
            self.meinPaymentButton.setBackgroundImage(UIImage(named: "payment_mine"), forState: UIControlState.Normal);
            
            self.notSurePaymentButton.enabled = true;
            self.notSurePaymentButton.setBackgroundImage(UIImage(named: "payment_not_sure"), forState: UIControlState.Normal);
        }
        
    }

    @IBAction func meinPayment(sender: UIButton) {
        if(sender.enabled){
            sender.enabled = false;
            self.paymentWay = "MINE";
            sender.setBackgroundImage(UIImage(named: "payment_mine_checked"), forState: UIControlState.Normal);
            self.aaPaymentButton.enabled = true;
            self.aaPaymentButton.setBackgroundImage(UIImage(named: "payment_aa"), forState: UIControlState.Normal);
            
            self.notSurePaymentButton.enabled = true;
            self.notSurePaymentButton.setBackgroundImage(UIImage(named: "payment_not_sure"), forState: UIControlState.Normal);
        }
        
    }
    
    @IBAction func notSurePayment(sender: UIButton) {
        if(sender.enabled){
            sender.enabled = false;
            self.paymentWay = "NOT_SURE";
            sender.setBackgroundImage(UIImage(named: "payment_not_sure_checked"), forState: UIControlState.Normal);
            self.aaPaymentButton.enabled = true;
            self.aaPaymentButton.setBackgroundImage(UIImage(named: "payment_aa"), forState: UIControlState.Normal);
            
            self.meinPaymentButton.enabled = true;
            self.meinPaymentButton.setBackgroundImage(UIImage(named: "payment_mine"), forState: UIControlState.Normal);
        }
    }
    
    @IBAction func clearInvitees(sender: UIButton) {
        self.willInvitationPersons = [];
        self.inviteesTextView.text = "";
        self.inviteesView.hidden = true;
    }
   
    func appointmentDate(date:NSDate){
        self.date = date;
    }
    
    func willInvitationPersons(willInvitationPersons:[NSDictionary]){
        self.willInvitationPersons = willInvitationPersons;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
    }
}
